package com.example.nio.niochat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioServer {
    private int port;
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;

    public NioServer(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);
        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("Server started on port " + port);
        while (true) {
            int select = selector.select();
            if (select > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        System.out.println("Accept connection...");
//                        SocketChannel channel = serverSocketChannel.accept();
                        ServerSocketChannel clientChannel = (ServerSocketChannel) key.channel();
                        SocketChannel channel = clientChannel.accept();

                        channel.configureBlocking(false);
                        channel.register(selector, SelectionKey.OP_READ);
                        // 必须清除
                        iterator.remove();
                    } else if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        socketChannel.read(byteBuffer);
                        String msg = new String(byteBuffer.array(), "UTF-8");
                        System.out.println("msg = " + msg);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        NioServer nioServer = new NioServer(5000);
        nioServer.start();
    }
}
